package com.oms.app.shop.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oms.app.address.service.IAddressService;
import com.oms.app.sequence.service.impl.SequenceManager;
import com.oms.app.shop.model.Shop;
import com.oms.app.shop.model.ShopMy;
import com.oms.app.shop.service.IShopService;
import com.oms.app.user.model.Role;
import com.oms.app.user.model.User;
import com.oms.app.user.service.IRoleService;
import com.oms.app.user.service.IUserService;
import com.oms.base.OMSConfigHolder;
import com.oms.page.PageModel;
import com.oms.util.OMSFileUtils;

/**
 * 商家相关业务
 * controller
 * @author wtj
 * @date Sep 2, 2012  6:23:59 PM
 */
@Controller
@RequestMapping("")
public class ShopAction {
	
	private static final String jspRootPath = OMSConfigHolder.getWebRoot().replaceAll("\\\\", "/") +  "jsp";
	private IShopService shopService;
	private IRoleService roleService;
	private IUserService userService;
	private IAddressService addressService;
	
	private Map<String, Object> map = new HashMap<String, Object>();
	
	public void setShopService(IShopService shopService) {
		this.shopService = shopService;
	}
	
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}
	
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	public void setAddressService(IAddressService addressService) {
		this.addressService = addressService;
	}
	
	//绑定时间格式
	@InitBinder  
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat, true));
    }
	
	//进入到商店管理页面
	@RequestMapping(value="/shop_shopManagerList")
	public String enterShopList(HttpServletRequest request) {
		return "manager/shop/shopManagerList";
	}
	
	// 获取商店列表
	@ResponseBody
	@RequestMapping(value="/shop_getList")
	public Map<String, Object> getShopList(HttpServletRequest request){
		List<Shop> list =  shopService.getShopList(request);
		return PageModel.getListToString(list, request);
	}
	
	//增加商店信息
	@ResponseBody
	@RequestMapping(value="/shop_addShop", method=RequestMethod.POST)
	public Map<String, Object> addShop(Shop shopForm, HttpServletRequest request){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		if (user != null) {
			shopForm.setCreator(user.getId());
		} else {
			shopForm.setCreator(Integer.valueOf(-1));
		}
		int shopId = shopService.addShop(shopForm);
		if (shopId != -1) {
			map.clear();
			map.put("id", new Integer(SequenceManager.nextID("address_relation")));
			map.put("type", Integer.valueOf(2)); //商家地址
			map.put("mainid", Integer.valueOf(shopId));
			map.put("addressid", Integer.valueOf(request.getParameter("addressid")));
			map.put("placename", request.getParameter("placename"));
			map.put("addressdetail", shopForm.getShopaddress());
			addressService.saveAddressRelation(map);
			
			jsonMap.put("success", true);
			jsonMap.put("msg", "增加商家成功！");
		} else {
			jsonMap.put("success", false);
			jsonMap.put("msg", "增加商家失败！");
		}
		return jsonMap;
	}
	
	//修改商家信息
	@ResponseBody
	@RequestMapping(value="/shop_updateShop/{shopId}", method=RequestMethod.POST)
	public Map<String, Object> updateShop(Shop shopForm, @PathVariable String shopId, HttpServletRequest request){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		shopForm.setId(Integer.valueOf(shopId));
		if (shopService.updateShop(shopForm)) {
			//先清空原商家关联地址
			map.clear();
			map.put("mainid", shopId);
			map.put("type", Integer.valueOf(2)); //商家地址
			addressService.deleteAddressRelation(map);
			//添加 商家/地址 关系
			map.put("id", new Integer(SequenceManager.nextID("address_relation")));
			map.put("addressid", Integer.valueOf(request.getParameter("addressid")));
			map.put("placename", request.getParameter("placename"));
			map.put("addressdetail", shopForm.getShopaddress());
			addressService.saveAddressRelation(map);
			
			jsonMap.put("success", true);
			jsonMap.put("msg", "修改商家成功！");
		} else {
			jsonMap.put("success", false);
			jsonMap.put("msg", "修改商家失败！");
		}
		return jsonMap;
	}
	
	//删除商家信息 如果包含子记录则不能删除
	@ResponseBody
	@RequestMapping(value="/shop_deleteShop/{shopId}")
	public Map<String, Object> deleteShop(@PathVariable String shopId, HttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (!shopService.isOrderFood(shopId)) {
			if (shopService.deleteShop(shopId)) {
				jsonMap.put("success", true);
				jsonMap.put("msg", "删除商家成功！");
			} else {
				jsonMap.put("success", false);
				jsonMap.put("msg", "删除商家失败！");
			}
		} else {
			jsonMap.put("success", false);
			jsonMap.put("msg", "商家包含食品记录和订单记录，请删除后再删除商家！");
		}
		return jsonMap;
	}
	
	//审批商家
	@ResponseBody
	@RequestMapping(value="/shop_changeShopStatus/{shopId},{status},{creator}")
	public Map<String, Object> changeShopStatus(@PathVariable String shopId, @PathVariable String status, @PathVariable String creator, HttpServletRequest request) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if (shopService.changeShopStatus(shopId, (("0".equals(status) || "2".equals(status)) ? "1" : "0"))) {
			if (("0".equals(status) || "2".equals(status))) { // 审核通过 赋予权限
				//添加角色
				Role role = roleService.getShopManagerRole();
				int roleId = -1;
				if (role == null) {
					roleId = SequenceManager.nextID("role");
					role.setId(roleId);
					role.setRolename("商家管理员");
					role.setDescription("商家管理员");
					roleService.saveOrUpdateRole(role);
				} else {
					roleId = role.getId().intValue();
				}
				//角色、模块关系
				map.clear();
				map.put("moduleid", "10010"); //此处为模块ID 动态查询 商家管理模块主键
				map.put("roleid", Integer.valueOf(roleId));
				if (!roleService.isRoleModule(map)) {
					map.put("id", Integer.valueOf(SequenceManager.nextID("role_module")));
					roleService.roleAddModule(map);
				}
				//角色、用户关系
				map.put("userid", creator);
				if (!userService.isUserRole(map)) {
					userService.userAddRole(map);
				}
				map.clear();
			}
			jsonMap.put("success", true);
			jsonMap.put("msg", "操作成功！");
		} else {
			jsonMap.put("success", false);
			jsonMap.put("msg", "操作失败！");
		}
		return jsonMap;
	}
	
	//商家管理-添加地区树页面
	@RequestMapping(value="/address_enterShopAddressTree/{type}")
	public void enterShopAddressTree(@PathVariable int type, HttpServletRequest request, HttpServletResponse response) {
		try {
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() + request.getContextPath();
			PrintWriter out = response.getWriter();
			File file = new File(jspRootPath + "/manager/shop/addressTree.jsp");
			String jspOut = OMSFileUtils.readFileToString(file, "UTF-8").replaceAll("\\{base\\}", basePath);
			jspOut = (type == 1) ? jspOut.replaceAll("a_addressID", "m_addressID") : jspOut;
			out.print(jspOut);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//######################### front 前台页面 ##############################################
	//获取我申请的商家列表
	@RequestMapping(value="/shop_allAllowMyShop/{creator}")
	public String allAllowMyShop(@PathVariable String creator, HttpServletRequest request) {
		List<Shop> list =  shopService.getMyApplyList(creator);
		request.setAttribute("myApplyList", list);
		return "front/one/shop/allAllowMyShop";
	}
	
	@RequestMapping(value="shop_applyShop")
	public String applyShop(HttpServletRequest request){
		return "front/one/shop/applyShop";
	}
	//获取我已经申请的商家
	@ResponseBody
	@RequestMapping(value="/shop_myShopList/{usid}")
	public Map<String, Object> shop_myShopList(@PathVariable String usid){
		map.clear();
		map.put("usid", usid);
		List<Map<String, Object>> list =  shopService.getMyShopList(map);
		System.out.println("2012年10月29日22:37:16 ： "+list);
		map.put("shoplist", list);
		return map;
	}
	//审批商家
	@ResponseBody
	@RequestMapping(value="/shop_getShopList")
	public Map<String, Object> shop_getShopList(){
		map.clear();
		List<Map<String, Object>> list =  shopService.getShopList(map);
		map.put("shoplist", list);
		return map;
	}
	//进入我的订单页面
	@RequestMapping(value="/shop_myOrderList")
	public String myOrderList(HttpServletRequest request) {
		return "front/one/shop/myOrderList";
	}
	
	//获取我的订单
	@ResponseBody
	@RequestMapping(value="/shop_getMyOrderList/{creator}") 
	public Map<String, Object> shop_getMyOrderList(@PathVariable String creator, HttpServletRequest request) {
		map.clear();
		if (creator == null) {
			User user = (User) request.getSession(true).getAttribute("user");
			creator = String.valueOf(user.getId());
		}
		map.put("creator", creator);
		List<Map<String, Object>> list = shopService.getMyOrderList(map);
		map.clear();
		map.put("orderlist", list);
		return map;
	}
	
	//进入我的订单详细信息列表页面
	@RequestMapping(value="/shop_myOrderDetailList/{shopId}")
	public String myOrderDetailList(@PathVariable String shopId, HttpServletRequest request) {
		request.setAttribute("shopId", shopId);
		return "front/one/shop/myOrderDetailList";
	}
	
	//获得某个商家的某个用户的订单详细列表
	@ResponseBody
	@RequestMapping(value="/shop_getMyOrderDetailList/{shopId}") 
	public Map<String, Object> shop_getMyOrderDetailList(@PathVariable String shopId, HttpServletRequest request) {
		map.clear();
		User user = (User) request.getSession(true).getAttribute("user");
		map.put("usId", user.getId());
		map.put("shopId", shopId);
		List<Map<String, Object>> list = shopService.getMyOrderDetailList(map);
		map.clear();
		map.put("detaillist", list);
		return map;
	}
	
	//更改某个订单的详细订单
	@ResponseBody
	@RequestMapping(value="/shop_changeOrderDetailStatus/{detailId},{status}")
	public Map<String, Object> changeOrderDetailStatus(@PathVariable String detailId, @PathVariable String status, HttpServletRequest request) {
		map.clear();
		if (shopService.changeOrderDetailStatus(detailId, status)) {
			map.put("success", true);
			map.put("msg", "操作成功！");
		} else {
			map.put("success", true);
			map.put("msg", "操作失败！");
		}
		return map;
	}
	
	//删除某个订单的详细订单信息
	@ResponseBody
	@RequestMapping(value="/shop_deleteOrderDetails/{detailIds}")
	public Map<String, Object> changeOrderDetailStatus(@PathVariable String detailIds, HttpServletRequest request) {
		map.clear();
		if (shopService.deleteOrderDetails(detailIds)) {
			map.put("success", true);
			map.put("msg", "删除订单成功！");
		} else {
			map.put("success", true);
			map.put("msg", "删除订单失败！");
		}
		return map;
	}
	
	//############################ 后台 店铺管理（ 店铺管理员 ） ########################################
	
	// 我的店铺管理页面
	@RequestMapping(value="/shop_myShopManager/{shopId}")
	public String myShopManager(@PathVariable String shopId,HttpServletRequest request) {
		System.out.println("2012年11月14日21:15:30 ： "+shopId);
		request.setAttribute("shopId", shopId);
		return "manager/shop/myShopManager";
	}
	
	// 店铺管理员管理已经申请的用户
	@ResponseBody
	@RequestMapping(value="/shop_getApplyUserList/{shopId}")
	public Map<String, Object> getApplyUserList(@PathVariable String shopId,HttpServletRequest request) {
		map.clear();
		map.put("list", shopService.getApplyUserList(shopId));
		return map;
	}
	
	//############################ 前台 ########################################
	//保存用户与商家申请关系信息
	@ResponseBody
	@RequestMapping(value="/shop_saveApplyShop")
	public Map<String, Object> saveApplyShop(ShopMy shopMy) {
		map.clear();
		if (!shopService.isAppliedShop(shopMy.getShopid(), shopMy.getUsid())) { //未存在用户与商家关系 则添加
			if (shopService.saveApplyShop(shopMy)) {
				map.put("success", true);
				map.put("msg", "操作成功！");
			} else {
				map.put("success", false);
				map.put("msg", "操作失败！");
			}
		}
		return map;
	}
	
}